const path = require("path");
const fs = require("fs-extra");
const config = require("./config");
const { bookshelf, Models, Mysql } = require("./model");
// 全局
global.BaaS = {};
global.BaaS.bookshelf = bookshelf;
global.BaaS.Models = Models;
global.BaaS.Mysql = Mysql;

(async () => {
  const baasList = await Models.baas.query({}).fetchAll();
  // 修改baas应用对应的数据库名称
  for (const key in baasList) {
    const domain = await Models.domain
      .query({
        where: { baas_id: baasList[key].id }
      })
      .fetch();
    if (!domain) {
      await Models.domain
        .forge({
          baas_id: baasList[key].id,
          name: `${baasList[key].appid}.dev.qingful.com`
        })
        .save();
    }
    // try {
    //   await Mysql.rename_database(
    //     "baas_" + baasList[key].appkey,
    //     "baas_" + baasList[key].appid
    //   );
    // } catch (err) {
    //   console.log("err", err);
    // }
    // const databaseName = "baas_" + baasList[key].appid;
    //     await Models.baas
    //       .forge({ id: baasList[key].id, database: databaseName })
    //       .save();
    //     await fs.ensureDir(path.resolve(config.web, baasList[key].appid));
    //     await fs.outputFile(
    //       path.resolve(config.nginx, `${baasList[key].appid}.conf`),
    //       `server {
    //   listen 80;
    //   server_name ${baasList[key].appid}.dev.qingful.com; #主机名称，绑定的域名
    //   root /www/baas-web/${baasList[key].appid};
    //   location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
    //       expires 30d;
    //   }
    //   location ~ .*\.(js|css)$ {
    //       expires 10d;
    //   }
    //   location / {
    //       index index.html index.htm index_prod.html;
    //   }
    // }`
    //     );
  }

  process.exit();
})();
